
import 'dart:async';

import 'package:flutter_base_library/flutter_base_library.dart';

/// BaseListControllerMixin
mixin BaseListControllerMixin<T> on GetxController {

  final RefreshController _refreshController = RefreshController(initialRefresh: false);
  RefreshController get refreshController => _refreshController;

  /// 初始页码, 默认为1
  int initPage = 1;

  int currentPage = 1;
  int pageSize = 10;
  bool hasMore = true;
  bool isRefreshing = false;
  bool isLoadingMore = false;
  String? errorMessage = '';

  List<T> dataList = [];

  @protected
  String get builderId;

  /// 是否监听生命周期
  bool get listenLifecycleEvent => false;

  late StreamSubscription refreshUiSubscription;

  StreamSubscription? lifecycleSubscription;

  @override
  void onInit() {
    super.onInit();
    refreshUiSubscription = eventListen<RefreshUIEvent>((event) {
      // 延时刷新UI
      delayed(300, () {
        GlobalService.to.updateNavigationBar();
        updateUi();
      });
    });
    if (listenLifecycleEvent) {
      lifecycleSubscription = eventListen<LifecycleEvent>((event) {
        switch (event.state) {
          case AppLifecycleState.resumed:
            onResumed();
            break;
          case AppLifecycleState.inactive:
            onInactive();
            break;
          case AppLifecycleState.detached:
            onDetached();
            break;
          case AppLifecycleState.paused:
            onPaused();
            break;
          case AppLifecycleState.hidden:
            onHidden();
            break;
        }
      });
    }
  }

  void onResumed() {}

  void onInactive() {}

  void onDetached() {}

  void onPaused() {}

  void onHidden() {}

  @override
  void onClose() {
    refreshUiSubscription.cancel();
    lifecycleSubscription?.cancel();
    _refreshController.dispose();
    super.onClose();
  }

  /// 返回
  void back() {
    Get.back();
  }

  /// 延时退出
  void delayedBack({int seconds = 2, result}) {
    Future.delayed(Duration(seconds: seconds), () {
      if (result != null) {
        Get.back(result: result);
      } else {
        Get.back();
      }
    });
  }

  /// 刷新UI
  void updateUi() {
    update([builderId]);
  }

  /// 刷新
  Future<void> onRefresh() async {
    if (isRefreshing) return;

    isRefreshing = true;
    errorMessage = '';
    currentPage = initPage;

    try{
      final List<T> result = await loadData(currentPage, pageSize);
      dataList.assignAll(result);
      hasMore = result.length >= pageSize;
      refreshController.refreshCompleted();

      if (result.isEmpty){
        refreshController.loadNoData();
      }
    }catch(e){
      errorMessage = e.toString();
      refreshController.refreshFailed();
    } finally {
      isRefreshing = false;
      updateUi();
    }
  }

  /// 加载更多
  Future<void> loadMore() async {
    if (!hasMore || isLoadingMore || isRefreshing){
      refreshController.loadNoData();
      return;
    }

    isLoadingMore = true;
    errorMessage = '';

    try{
      final List<T> result = await loadData(currentPage, pageSize);
      dataList.addAll(result);
      hasMore = result.length >= pageSize;
      refreshController.loadComplete();
    } catch(e){
      currentPage--;
      errorMessage = e.toString();
      refreshController.loadFailed();
    } finally {
      isLoadingMore = false;
      updateUi();
    }
  }

  Future<List<T>> loadData(int page, int pageSize);

}
